const { createOrUpdate, findCarts, updateCarts, removeCarts, selectAllCarts, unselectAllCarts } = require('../service/cart.service')
const { cartFormatError } = require('../constant/err.type')
class CartController {
    async add(ctx) {
        const user_id = ctx.state.user.id;// 获的用户id
        const goods_id = ctx.request.body.goods_id // 获取商品id
        console.log(user_id, goods_id);
        // ctx.body = '金合欢花哈'

        const res = await createOrUpdate(user_id, goods_id)
        ctx.body = {
            code: 0,
            message: "添加购物车成功",
            rulest: res
        }
    }

    async findAll(ctx, next) {
        // 解析数据
        const { page = 1, gageSize = 10 } = ctx.request.query;
        // 操作数据库
        const res = await findCarts(page, gageSize);
        // 
        ctx.body = {
            code: 0,
            message: "获取购物车列表成功",
            rulest: res,
        }
    }

    async update(ctx, next) {
        // 解析参数
        const { id } = ctx.request.params
        const { number, selected } = ctx.request.body
        if (number === undefined && selected === undefined) {
            cartFormatError.message = 'number和selected同时为空'
            return ctx.app.emit('error', cartFormatError, ctx)
        }

        // 操作数据库
        const res = await updateCarts({ id, number, selected })
        ctx.body = {
            code: 0,
            message: '',
            rulest: res
        }
    }

    async remove(ctx) {
        const { ids } = ctx.request.body

        const res = await removeCarts(ids);

        ctx.body = {
            code: 0,
            message: "删除购物车成功",
            result: res,
        }
    }

    async selectAll(ctx) {
        const user_id = ctx.state.user.id

        const res = await selectAllCarts(user_id, true);
        ctx.body = {
            code: 0,
            message: "全部选中",
            result: res
        }
    }

    async unselectAll(ctx) {
        const user_id = ctx.state.user.id

        const res = await selectAllCarts(user_id, false);
        ctx.body = {
            code: 0,
            message: "全部不选中",
            result: res
        }
    }
}

module.exports = new CartController()